package com.itheima.controller;


//员工管理控制层类

import com.itheima.commo.PageResult;
import com.itheima.commo.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


    //后台登录功能
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession httpSession) {
        try {
            //登录业务处理 希望返回R结果对象
            return employeeService.login(employee, httpSession);
        } catch (Exception e) {
            log.debug("*******登陆失败了*******");
            return R.error("登陆失败了");
        }
    }

    //退出
    @PostMapping("/logout")
    public R<String> logout(HttpSession httpSession) {
        try {
            employeeService.logout(httpSession);
            return R.success("退出成功了");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("退出失败了");
        }
    }

    //新增员工
    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpSession httpSession) {
        Employee ey = (Employee) httpSession.getAttribute("employee");
        int row = employeeService.save(employee, ey.getId());
        if (row == 1) {
            return R.success(null, "新增成功");
        } else {
            return R.error("新增失败");
        }
    }


    //员工分页信息
    @GetMapping("/page")
    public R<PageResult> findPage(@RequestParam(value = "page", defaultValue = "1") Long page,
                                  @RequestParam(value = "pageSize", defaultValue = "10") Long pageSize, String name) {
        PageResult<Employee> pageResult = employeeService.findPage(page, pageSize, name);
        return R.success(pageResult);
    }

    //更新员工
    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession HttpSession){
        Employee ey = (Employee) HttpSession.getAttribute("employee");
        int row =  employeeService.update(employee, ey.getId());
        if (row == 1 ){
            return R.success(null, "修改成功了");
        }else {
            return R.error("修改失败了");
        }
    }

    // 根据员工id查询员工信息
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable("id") Long id){
        Employee employee = employeeService.findById(id);
        return R.success(employee);
    }


}
